#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import config as c
from gitlab_map import site_map
import os
import re
from ftplib import FTP

root_path = c.local_www_path
# tpl_file_path = '/common/models/WorldpayLog.php'
tpl_file_path = '/api/order_module.php'

pattern1 = "self\:\:getOrderDetailAttrs\(\$id\)\;"
new_str1 = ''' self::getOrderDetailAttrs($id);
                    $list[$key]['gift_box_sku'] = self::getGiftBoxSku($value, $list[$key]['attrs']);'''

pattern2 = "public static function getOrderInfo"
new_str2 = '''/**
     * 获取礼盒SKU，其中有几种情况
     */
    public static function getGiftBoxSku($detail, $attr) 
    {
        $db = self::getDb();

        // 如果attrs有sku这个商品就按子sku作为依据，如果没有默认父级sku作为依据；如果都找不到，就取默认礼盒
        $finalSku = $detail['sku'];
        // 父子sku依据的判断标识 0就是父sku， 1就是子sku
        $skuFlag = 0;
        if (!empty($attr)) {
            foreach ($attr as $k => $v) {
                if (!empty($v['sku'])) {
                    $finalSku = $v['sku'];
                    $skuFlag ++;
                    break;
                }
            }
        }
        // 如果是配置成不需要礼盒，这个字段就是空
        if (!$skuFlag) {
            $sql = "SELECT need_gift_box FROM t_goods WHERE g_sku = '{$finalSku}'";
            $need = $db->getRow($sql);
            if ($need && $need['need_gift_box'] == 0) {
                return '';
            }
        } else {
            $sql = "SELECT c.* FROM t_goods AS a LEFT JOIN t_goods_cs_attr AS b ON a.g_id = b.g_id
                LEFT JOIN t_goods_cs_attr_value AS c ON b.ca_id = c.ca_id 
                WHERE ca_deleted = 0 AND cv_deleted = 0 AND c.sku = '{$finalSku}' GROUP BY c.sku";
            $info = $db->getRow($sql);
            if ($info && $info['need_gift_box'] == 0) {
                return '';
            }
        }
        // 看下有没有配置特殊礼盒
        $sql = "SELECT * FROM gift_box_set WHERE g_sku = '{$finalSku}'";
        $specialRet = $db->getRow($sql);
        // 如果有特殊礼盒配置就是特殊礼盒sku
        if ($specialRet) {
            $giftBoxSku = $specialRet['gbs_sku'];
        } else {
            // 否则就是通用礼盒
            $sql = "SELECT * FROM gift_box_set WHERE gbs_special_set = 0";
            $commonRet = $db->getRow($sql);
            if ($commonRet) $giftBoxSku = $commonRet['gbs_sku'];
        }

        return $giftBoxSku;
    }

    public static function getOrderInfo'''

def alter(file, new_str, pattern):
    try:
        with open(file, "r", encoding="utf-8") as f1, open("%s.bak" % file, "w", encoding="utf-8") as f2:
            content = f1.read()
            match_ret = re.search(pattern, content)
            flag = False

            if match_ret is None:
                print(file + ' ***** 异常: None,未匹配到 *****')
            else:
                text = re.sub(pattern, new_str, content)
                f2.write(text)
                flag = True

        if flag == True:
            os.remove(file)
            os.rename("%s.bak" % file, file)
            print(file + ' >>> 已完成')
    except Exception as e:
        print(file + ' ***** 异常 ***** >>> ' + str(e))

if __name__ == "__main__":
    for i in c.dirname_list:
        i = i.lower()
        dirname = site_map[i][35:][:-4].lower()
        project_path = root_path + dirname
        tpl = project_path + tpl_file_path
        alter(tpl, new_str1, pattern1)
        alter(tpl, new_str2, pattern2)